// 获取当前标签页URL
async function getCurrentTabUrl() {
  const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
  if (tabs.length === 0) {
    throw new Error('No active tab found');
  }
  return tabs[0].url;
}

// 更新状态显示
function updateStatus(message, isError = false) {
  const status = document.getElementById('status');
  status.textContent = message;
  status.className = isError ? 'error' : 'success';
}

// 更新Cookie计数
function updateCookieCount(count) {
  const countElement = document.getElementById('cookieCount');
  countElement.textContent = `共找到 ${count} 个Cookie`;
}

// 更新Cookie详情显示
function updateCookieDetails(cookies) {
  const details = document.getElementById('cookieDetails');
  const formattedDetails = cookies.map(cookie => {
    return `${cookie.name} = ${cookie.value}
域: ${cookie.domain}
路径: ${cookie.path}
过期: ${cookie.expirationDate ? new Date(cookie.expirationDate * 1000).toLocaleString() : '会话结束'}
HttpOnly: ${cookie.httpOnly}
Secure: ${cookie.secure}
SameSite: ${cookie.sameSite}
------------------------`;
  }).join('\n');
  
  details.textContent = formattedDetails || '没有找到Cookie';
}

// 检查域名是否匹配
function isMatchingDomain(domain) {
  return domain === '.xiaohongshu.com' || domain === 'www.xiaohongshu.com';
}

// 获取cookie并复制到剪贴板
async function getCookieAndCopy() {
  try {
    // 获取当前标签页URL
    const url = await getCurrentTabUrl();
    const urlObj = new URL(url);
    
    // 检查是否在小红书网站
    if (!urlObj.hostname.includes('xiaohongshu.com')) {
      updateStatus('请在小红书网站使用此插件', true);
      return;
    }

    // 获取所有cookie
    const allCookies = await chrome.cookies.getAll({
      domain: 'xiaohongshu.com'
    });

    // 过滤并排序cookie
    const filteredCookies = allCookies
      .filter(cookie => isMatchingDomain(cookie.domain))
      .sort((a, b) => {
        // 定义cookie的预期顺序
        const order = [
          'gid',
          'a1',
          'webId',
          'acw_tc',
          'abRequestId',
          'webBuild',
          'web_session',
          'unread',
          'xsecappid',
          'loadts',
          'websectiga',
          'sec_poison_id'
        ];
        
        const indexA = order.indexOf(a.name);
        const indexB = order.indexOf(b.name);
        
        // 如果两个cookie都在预定义顺序中
        if (indexA !== -1 && indexB !== -1) {
          return indexA - indexB;
        }
        // 如果只有一个cookie在预定义顺序中
        if (indexA !== -1) return -1;
        if (indexB !== -1) return 1;
        // 如果都不在预定义顺序中，按名称字母顺序排序
        return a.name.localeCompare(b.name);
      });

    if (filteredCookies.length === 0) {
      updateStatus('未找到任何Cookie', true);
      updateCookieCount(0);
      updateCookieDetails([]);
      return;
    }

    // 格式化cookie字符串
    const cookieStr = filteredCookies
      .map(cookie => `${cookie.name}=${cookie.value}`)
      .join('; ');

    // 复制到剪贴板
    await navigator.clipboard.writeText(cookieStr);
    
    // 更新界面显示
    updateStatus(`已复制 ${filteredCookies.length} 个Cookie到剪贴板！`);
    updateCookieCount(filteredCookies.length);
    updateCookieDetails(filteredCookies);
    
    // 在控制台输出详细信息（用于调试）
    console.log('获取到的Cookie:', filteredCookies);
    
  } catch (error) {
    console.error('获取Cookie时出错:', error);
    updateStatus('获取Cookie失败: ' + error.message, true);
    updateCookieCount(0);
    updateCookieDetails([]);
  }
}

// 切换详情显示
function toggleDetails() {
  const details = document.getElementById('cookieDetails');
  const button = document.getElementById('toggleDetails');
  const isVisible = details.style.display !== 'none';
  
  details.style.display = isVisible ? 'none' : 'block';
  button.textContent = isVisible ? '显示详情' : '隐藏详情';
}

// 添加事件监听器
document.addEventListener('DOMContentLoaded', () => {
  document.getElementById('getCookieBtn').addEventListener('click', getCookieAndCopy);
  document.getElementById('toggleDetails').addEventListener('click', toggleDetails);
});